package com.ccit.msm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ccit.model.vo.msm.MsmVo;
import com.ccit.msm.config.AliyunSmsConfig;
import com.ccit.msm.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class MsmServiceImpl implements MsmService {
    @Resource
    private AliyunSmsConfig aliyunSmsConfig;

    @Override
    public boolean send(String phone, String code) {
        if (StringUtils.isEmpty(phone)) return false;
//        //default 地域节点，默认就好  后面是 阿里云的 id和秘钥
//        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI5t7jj7NdCVeyHxo9PvaA", "p8EnN0HPKnJDog939Z3zCbyFpJ2MIe");
//        IAcsClient client = new DefaultAcsClient(profile);
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("code", Integer.parseInt(code));
//
//        CommonRequest request = new CommonRequest();
//        //request.setProtocol(ProtocolType.HTTPS);
//        request.setMethod(MethodType.POST);
//        request.setDomain("dysmsapi.aliyuncs.com");
//        request.setVersion("2017-05-25");
//        request.setAction("SendSms");
//
//        request.putQueryParameter("PhoneNumbers", phone);                    //手机号
//        request.putQueryParameter("SignName", "阿里云短信测试");    //申请阿里云 签名名称（暂时用阿里云测试的，自己还不能注册签名）
//        request.putQueryParameter("TemplateCode", "SMS_154950909"); //申请阿里云 模板code（用的也是阿里云测试的）
//        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));

        try {
            SendSmsResponse response = aliyunSmsConfig.sendSms(
                    phone,
                    "阿里云短信测试", // 阿里云短信签名
                    "SMS_154950909", // 阿里云短信模板代码
                    "{\"code\":\"" + code + "\"}" // 模板参数
            );
            log.info(response.getCode());
            return "OK".equals(response.getCode());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //mq发送短信封装
    @Override
    public boolean send(MsmVo msmVo) {
        if (!StringUtils.isEmpty(msmVo.getPhone())) {
            String code = (String) msmVo.getParam().get("code");
            boolean isSend = this.send(msmVo.getPhone(), code);
            return isSend;
        }
        return false;
    }
}
